package com.hmdp.interceptor;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.utils.JWTUtils;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.UserHolder;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.crypto.SecretKey;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.time.Duration;
import java.util.Map;

@RequiredArgsConstructor
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    private final StringRedisTemplate stringRedisTemplate;
    private final SecretKey secretKey;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取前端传来的token
        String token = request.getHeader("authorization");
        if (token == null) {
            return false;
        }
        try {
            //判断是否能被解析，不能则会抛出异常
            Claims claims = JWTUtils.parseJWT(secretKey, token);
            Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(RedisConstants.LOGIN_USER_KEY + token);
//            if (userMap.isEmpty() || !claims.get("id").equals(userMap.get("id"))) {
            if (userMap.isEmpty()) {
                response.setStatus(401);
                log.error("token不存在或者两者id不相等");
                return false;
            }

            log.info("token验证成功，可以访问");
            return true;
        } catch (Exception e) {
            log.error("token无法被正确解析，token疑似被更改！");
            response.setStatus(401);
            return false;
        }

//        HttpSession session = request.getSession();
//        User user = (User) session.getAttribute("user");
//        System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" + user + "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
//        if (user == null) {
//            response.setStatus(401);
//            return false;
//        }
//        UserDTO userDTO = new UserDTO();
//        BeanUtils.copyProperties(user, userDTO);
//        System.out.println("**************************" + userDTO + "&&&&&&&&&&&&&&&&&&&&&&&&&");
//        UserHolder.saveUser(userDTO);
//        System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^" + UserHolder.getUser() + ")))))))))))))))))))))))))))");
//        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
